#!/usr/bin/env python -OO
# -*- coding: utf-8 -*-

# Copyright © 2008,2009 Trust Digital Technology Laboratory, Shanghai Jiao Tong University.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# Author:
#   XING Dong sheng <homer.xing@gmail.com>

from __future__ import with_statement

__all__ = ['installlatex']

import os, sys
import tempfile
import softwaredependent as D
from softwareindependent import getArch, TempOwn

def update_etc_environment():
    fn='/etc/environment'
    with TempOwn(fn) as o:
        with open(fn, "r+") as f:
            content = f.readlines()
            if not ("texlive" in content[0]):
                if getArch()==64:
                    added = "/usr/local/texlive/2008/bin/x86_64-linux"
                else:
                    added = "/usr/local/texlive/2008/bin/i386-linux"
                path = content[0]
                content[0] = path[:6]+added+":"+path[6:]
                f.seek(0,0) #定位到文件开头
                f.writelines(content)

def latexchinesefont():
    #FIXME 从2007升级到2008后，是否需要重做字体？
    D.download("texcjkfont")
    if D.execute("cd %s ; bunzip2 -fv %s" %(D.LOCAL, D.softwarelist["texcjkfont"]) ):
        f = D.softwarelist["texcjkfont"][:-4]
        if D.execute("cd %s && tar vxf %s" %(D.LOCAL, f) ):
            #FIXME YueWang没有发布 Texlive 2008 用的中文字体！
            D.execute("rm -rf ~/.texlive2008; mv %s/.texlive2007 %s/.texlive2008"%(D.LOCAL,D.HOME) )
            D.execute("fmtutil --all >/dev/null 2>/dev/null")

def latexcompilescript():
    D.execute("sudo cp %s /usr/local/bin/; sudo chmod a+x /usr/local/bin/texpdf"%(D.FILES+"texpdf") )

def latextemplate():
    D.execute("cp %s ~/桌面/"%(D.FILES+"tex4paper.tex") )

def latexsuite():
    if D.install("vim-gnome"):
        D.execute("mkdir %s/.vim"%D.HOME)
        f=D.download("texsuite")
        if D.execute("cd %s/.vim/; tar zxf %s"%(D.HOME, f) ):
            path = os.path.join(D.HOME, ".vimrc")
            try:
                with open( path , "r+") as f:
                    content=f.read()
            except:
                content = ''
            if not ("latex-suite" in content):
                D.execute("cat %s >> ~/.vimrc"%(D.FILES+"latexsuitevimrc") )
            D.execute("sudo cp %s /usr/local/bin/; sudo chmod a+x /usr/local/bin/texsuite"%(D.FILES+"texsuite") )
            D.execute("cp %s ~/Desktop/"%(D.FILES+"如何编辑编译latex") )

def installlatex():
    if os.path.exists("/usr/local/texlive/2008/"): return
    D.download("texlive")
    f = tempfile.NamedTemporaryFile(mode='w')
    f.write("I")
    f.flush()
    D.execute("sudo mkdir /mnt/texlive; sudo mount -t iso9660 -o iocharset=utf8,loop %s/%s /mnt/texlive; sudo /mnt/texlive/install-tl < %s >/dev/null 2>/dev/null" % (D.LOCAL,D.softwarelist["texlive"],f.name) )
    f.close()
    update_etc_environment()
    latexchinesefont()
    latexcompilescript()
    latextemplate()
    latexsuite()

if __name__ == "__main__":
    installlatex()
